angular.module('mamApp').controller('programManageController', ['$scope', 'ProgramAuditManager', '$state', 'api', 'FileUploader', 'ImsDialog', 'CommonManager', '$filter', '$sce','BaseValidations','$uibModal','ImsErr','$rootScope',
    function ($scope, ProgramAuditManager, $state, api, FileUploader, ImsDialog, CommonManager, $filter, $sce,BaseValidations,$uibModal,ImsErr,$rootScope) {
        $scope.$sce = $sce;
        $scope.BaseValidations = BaseValidations;

        $scope.list = [];
        $scope.failReason = [{key: 204, value: $scope.table[204]}, {key: 210, value: $scope.table[210]}, {
            key: 211,
            value: $scope.table[211]
        }, {key: 212, value: $scope.table[212]}]


        $scope.count = 10;
        setInterval(function () {
            if ($scope.count) {
                $scope.$apply($scope.count--);
            }
        }, 1000)
        $scope.formData={};
        $scope.image_a = false;
        $scope.uploaderAudio = new FileUploader({
            alias: "uploadFile",
            autoUpload: false,
            queueLimit: 1,//文件个数
            removeAfterUpload: true,//上传后删除文件 */
            filters: [{
                name: 'uploadFile',//后台接收字段
                fn: function (item /*{File|FileLikeObject}*/, options) {
                    if (!/\.(mp3|MP3|aac|AAC)$/.test(item.name)) {
                        $scope.imageMsg = "仅支持MP3、AAC格式";
                        $scope.image_a = true;
                        return false;
                    }
                    else if (item.size > 150 * 1024 * 1024 || item.size < 0.5 * 1024 * 1024) {
                        $scope.imageMsg = "仅可上传一个大小范围0.5-150M音频，";
                        $scope.image_a = true;
                        return false;
                    } else {
                        $scope.image_a = false;
                        return true;
                    }

                }
            }],
            onSuccessItem: function (fileItem, response, headers) {
                if (response.c == "s") {
                    delete  response.c;
                    $scope.formData.origAudioUrl = response.fileVO.webUrl
                    $scope.list.push({file: response.fileVO, audio: response.audioInfoVO});
                } else {
                    fileItem.isSuccess = false;
                    $scope.imageMsg = "上传  " + fileItem.file.name + " 失败，请重新添加上传";
                    $scope.image_a = true;
                }
            },
            url: api + "/admin/programs/audio?cpId="+$scope.formData.cpId,
            headers: {'X-Auth-Token': $scope.userInfo.token}
        })

        var programId = $state.params.programId;
        ProgramAuditManager.programDetail(programId).then(function (result) {

            $scope.formData = result.data.adminProgramVO;
            console.log($scope.formData.reviewErrorId,'qqq')
            $scope.reviewError=$filter('filter')( $scope.failReason,{key: $scope.formData.reviewErrorId})[0];
            $scope.statusChange =function(){
                $scope.formData.reviewErrorId = $scope.formData.reviewErrorId ? $scope.formData.reviewErrorId : 204;
            }


            $scope.formData.keyword = $scope.formData.keyword.join(",");
            $scope.uploaderAudio.url=api + "/admin/programs/audio?cpId="+$scope.formData.cpId;
            var tmpComm = [];
            var tmpSpe = [];
            $scope.formData.commList.forEach(function (tag) {
                tmpComm.push({
                    commtagId: tag.commtagId,
                    dimensionId: tag.dimensionId,
                    commtagName: tag.commtagName
                })
            })
            $scope.formData.specialList.forEach(function (tag) {
                tmpSpe.push({
                    specialId: tag.specialId,
                    dimensionId: tag.dimensionId,
                    specialName: tag.specialName
                })
            })
            $scope.commonTagsSelected = tmpComm;
            $scope.specialTagsSelected = tmpSpe;
            $scope.specialTagsList($scope.formData.channelId)

            CommonManager.categoriesList().then(function (result) {
                $scope.categories = result.data.pageList;
                $scope.categorySelected = $filter('filter')($scope.categories, {categoryId: $scope.formData.categoryId})[0];
                $scope.categoryChange($scope.categorySelected);

            })


        })


        $scope.categoryChange = function (category) {
            $scope.formData.categoryId = category.categoryId;
            CommonManager.channelList(category.categoryId).then(function (result) {
                $scope.channels = result.data.pageList;
                $scope.channelSelected = $filter('filter')($scope.channels, {channelId: $scope.formData.channelId})[0];

            })
        }
        CommonManager.commonTagsList().then(function (result) {
            $scope.commonTags = [];
            $scope.commonDimensionsName = {};
            result.data.pageList.forEach(function (item) {
                $scope.commonDimensionsName[item.dimensionId] = item.dimensionsName;
                if (item.hasOwnProperty("list")) {
                    item.list.forEach(function (tag) {
                        $scope.commonTags.push({
                            commtagId: tag.commtagId,
                            dimensionId: item.dimensionId,
                            commtagName: tag.commtagName
                        })
                    })
                }
            })
        })


        $scope.channelChange = function (channel) {
            $scope.specialTagsSelected = [];
            $scope.formData.channelId = channel.channelId;
            $scope.specialTagsList(channel.channelId);

        }
        $scope.specialTagsList = function (channelId) {
            $scope.specialTags = [];
            $scope.specialDimensionsName = {};

            CommonManager.specialTagsList(channelId).then(function (result) {
                if (result.data.pageList) {
                    result.data.pageList.forEach(function (item) {
                        $scope.specialDimensionsName[item.dimensionId] = item.dimensionsName;

                        if (item.hasOwnProperty("list")) {
                            item.list.forEach(function (tag) {
                                $scope.specialTags.push({
                                    specialId: tag.specialId,
                                    dimensionId: tag.dimensionId,
                                    specialName: tag.specialName
                                })
                            })
                        }

                    })
                }


            })
        }


        /**
         * 通用标签分组
         * @param item
         * @returns {*}
         */

        $scope.commGroupFn = function (item) {
            return $scope.commonDimensionsName[item.dimensionId]
        };
        /**
         * 通用标签分组
         * @param item
         * @returns {*}
         */

        $scope.specialGroupFn = function (item) {
            return $scope.specialDimensionsName[item.dimensionId]
        };


        $scope.uploaderAlbumCover = new FileUploader({
            alias: "uploadFile",
            autoUpload: true,
            queueLimit: 1,//文件个数
            // removeAfterUpload: true,//上传后删除文件 */
            filters: [{
                name: 'uploadFile',//后台接收字段
                fn: function (item /*{File|FileLikeObject}*/, options) {
                    if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(item.name)) {
                        $scope.imageMsg = "格式不正确";
                        return false;
                    }
                    else if (item.size > 2 * 1024 * 1024) {
                        $scope.imageMsg = "图片大小2M以下";
                        return false;
                    } else {
                        return true;
                    }

                }
            }],
            onSuccessItem: function (fileItem, response, headers) {
                if (response.c == "s") {
                    $scope.formData.programCover = response.fileVO.webUrl;
                } else {
                    fileItem.isSuccess = false;
                    alert("上传  " + fileItem.file.name + " 失败，请删除后重新添加上传");
                }
            },
            url: api + "/admin/programs/cover",
            headers: {'X-Auth-Token': $scope.userInfo.token}
        })

/*

        var handleFileSelect = function (evt) {
            var file = evt.currentTarget.files[0];
            $scope.uploadCover(file);

        };*/
        var handleFileSelect = function (evt) {
            var file = evt.currentTarget.files[0];
            if(file.type.indexOf("image")==-1){
                $scope.$apply($scope.errorImg='仅支持PNG/JPG/JPEG格式');
                return false;
            }else {
                $scope.$apply($scope.errorImg='');
            }

            $scope.uploadCover(file)
        };


        setTimeout(function () {
            angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect);
        }, 1000)

        $scope.uploadCover = function (image) {
            if(image.type.indexOf("image")==-1){
                $scope.$apply($scope.errorImg='仅支持PNG/JPG/JPEG格式');
                return false;
            }else {
                $scope.$apply($scope.errorImg='');
            }
            var modalInstance = $uibModal.open({
                animation: true,
                backdrop:false,
                templateUrl: 'uploadCover.html',
                controller: 'coverManageController',
                resolve: {
                    params: function () {
                        return {image: image,coverType:'program',cpId:$scope.formData.cpId};
                    }
                }
            });
            modalInstance.result.then(function (result) {
                $("#fileInput").prop("value","");
                if (result.url) {
                    $scope.formData.programCover = result.url


                }

            })
        }


        $scope.reviewErrorChange=function (reviewError) {
            $scope.formData.reviewErrorId=reviewError.key;
        }




        $scope.cancel = function () {
            if ($state.current.name == "main.album.program.edit") {
                $state.go("main.album.program", {albumId: $scope.albumId}, {reload: true, inherit: false})
            } else {
                $state.go("main.programAudit", {}, {reload: true, inherit: false})
            }

        }

        $scope.submit = function () {
            var file = {
                "filePath": $scope.formData.origAudioFilePath,
                "webUrl": $scope.formData.origAudioUrl,
                "fileOrigName": $scope.formData.origAudioName,
                "fileSize": $scope.formData.origAudioFileSize
            };
            var audio = {
                "duration": $scope.formData.origAudioDuration,
                "bitRate": $scope.formData.origAudioBitRate,
                "channels": $scope.formData.origAudiochannels,
                "samplingRate": $scope.formData.origAudioSamplingRate
            }
            var commTag = [];
            var specialTag = [];
            $scope.commonTagsSelected.forEach(function (item) {
                commTag.push(item.commtagId)
            })
            $scope.specialTagsSelected.forEach(function (item) {
                specialTag.push(item.specialId)
            })
            if ($scope.formData.reviewStatus == 8) {
                $scope.formData.reviewErrorId = "";
                $scope.formData.reviewErrorMemo = "";
            }


            ImsDialog.open({title: "节目审核", message: "确定提交节目资料以及认证信息？"}).then(function (a) {
                if (a == "ok") {
                    delete $scope.formData.duration;
                    var tmpToSave = {
                        albumId: $scope.formData.albumId,
                        programId: $scope.formData.programId,
                        programName: $scope.formData.programName,
                        isExtend: $scope.formData.isExtend,
                        programCover: $scope.formData.programCover,
                        commTag: commTag.join(","),
                        specialTag: specialTag.join(","),
                        keyword: $scope.formData.keyword ? $scope.formData.keyword.split(",") : [],
                        anchorName: $scope.formData.anchorName,
                        originalName: $scope.formData.originalName,
                        summary: $scope.formData.summary,
                        reviewStatus: $scope.formData.reviewStatus,
                        reviewErrorId: $scope.formData.reviewErrorId,
                        reviewErrorMemo: $scope.formData.reviewErrorMemo,
                        file: $scope.list.length ? $scope.list[0].file : file,
                        audio: $scope.list.length ? $scope.list[0].audio : audio
                    };
                    ProgramAuditManager.programEdit(programId, tmpToSave).then(function (result) {
                        if (result.data.c == "s") {
                            $scope.cancel()
                        }else{
                            ImsErr.open({title: "提示", message: result.data.i}).then(function (a) {
                                $state.reload()
                            })
                        }
                    })
                }
            })

        }
        //播放器

    }]);

